package com.ulook.lookplanet.ui.notifications;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.base.BaseFragment;
import com.ulook.lookplanet.data.model.BaseUser;
import com.ulook.lookplanet.data.model.TSysMsg;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.main.MainActivity;
import com.ulook.lookplanet.service.SysMsgService;
import com.ulook.lookplanet.service.UserMsgService;
import com.ulook.lookplanet.ui.notifications.friend.FriendActivity;
import com.ulook.lookplanet.widget.MsgView;

import java.util.HashMap;

public class NotificationsFragment extends BaseFragment {

    private View root;
    private NotificationsViewModel viewModel;
    private LinearLayout msgLayout;

    private UserMsgLocalReceiver userMsgLocalReceiver;
    private SysMsgLocalReceiver sysMsgLocalReceiver;
    private LocalBroadcastManager localBroadcastManager;


    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(this).get(NotificationsViewModel.class);
        root = inflater.inflate(R.layout.fragment_notifications, container, false);
        viewModel.getToastText().observe(getViewLifecycleOwner(), s -> {
            Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
        });



        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 判断登陆状态
        BaseUser user = ((MainActivity)getActivity()).getCurrUser();
        if(user.getId() != 0){
            viewModel.setCurrUser((TUser) user);
        }

        initTopBar();
        initData();


    }

    @Override
    public void onResume() {
        // 注册广播
        Log.d("#####", "注册广播");
        registerMsgReceive();
        super.onResume();
    }

    @Override
    public void onPause() {
        // 注销本地广播监听器
        Log.d("#####", "注销本地广播监听器");
        unregisterMsgReceive();
        super.onPause();
    }

    /**
     * 初始化导航条
     */
    private void initTopBar(){
        QMUITopBarLayout topBar = root.findViewById(R.id.notif_bar);
        topBar.setTitle(R.string.title_notifications);
        if(viewModel.getCurrUser() == null){
            return;
        }
        topBar.addRightImageButton(R.drawable.ic_corn_user, 0).setOnClickListener(view -> {
            //  跳转好友列表
            Intent intent = new Intent(getActivity(), FriendActivity.class);
            intent.putExtra("currUserId", viewModel.getCurrUser().getId());
            startActivity(intent);
        });
    }

    /**
     * 初始化数据
     */
    private void initData(){
        Log.d("#####", viewModel.getCurrUser().toString());
        if(viewModel.getCurrUser() == null){
            return;
        }
        msgLayout = root.findViewById(R.id.notif_layout);
        // 系统通知
        MsgView sysMsgView = new MsgView(getActivity());
        sysMsgView.setWidgetData(new VMsgSys(), viewModel.getCurrUser().getId());
        msgLayout.addView(sysMsgView);
        // 用户通知, 初始化消息列表
        HashMap<Integer, VMsgUser> users = viewModel.getChatList();
        for(int key : users.keySet()){
            MsgView userMsgView = new MsgView(getActivity());
            Log.d("######Notif", users.get(key).toString());
            userMsgView.setWidgetData(users.get(key), viewModel.getCurrUser().getId());  // 设置最新一条消息内容
            userMsgView.setPoint(viewModel.getUnreadNum(key));  // 设置未读消息条数
            msgLayout.addView(userMsgView);
        }
    }

    /**
     * 注册MsgService的广播
     */
    private void registerMsgReceive(){
        Log.d("#####","注册MsgService的广播");
        localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        // 用户消息广播
        IntentFilter userFilter = new IntentFilter();
        userFilter.addAction(UserMsgService.INTENT_ACTION);
        userMsgLocalReceiver = new UserMsgLocalReceiver();
        localBroadcastManager.registerReceiver(userMsgLocalReceiver, userFilter);
        // 系统消息广播
        IntentFilter sysFilter = new IntentFilter();
        sysFilter.addAction(SysMsgService.INTENT_ACTION);
        sysMsgLocalReceiver = new SysMsgLocalReceiver();
        localBroadcastManager.registerReceiver(sysMsgLocalReceiver, sysFilter);
    }

    /**
     * 注销广播
     */
    private void unregisterMsgReceive(){
        localBroadcastManager.unregisterReceiver(userMsgLocalReceiver);
        localBroadcastManager.unregisterReceiver(sysMsgLocalReceiver);
    }

    // 广播，接收数据
    class UserMsgLocalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("#####","UserMsgLocalReceiver");
            VMsgUser vMsgUser = (VMsgUser) intent.getSerializableExtra("msg");
            getNewUserMsg(vMsgUser);
        }
    }
    class SysMsgLocalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("#####","SysMsgLocalReceiver");
            TSysMsg sysMsg = (TSysMsg) intent.getSerializableExtra("msg");
            getNewSysMsg(sysMsg);
        }
    }

    /**
     * 接收到新的用户消息
     */
    private void getNewUserMsg(VMsgUser msgUser){
        int count = msgLayout.getChildCount();
        int i = 0;
        while (i < count){
            MsgView msgView = (MsgView) msgLayout.getChildAt(i);
            if(msgView.getFromUserId() == msgUser.getFromuser()){
                msgView.setMsgContent(msgUser.getMsg());
                msgView.setPoint(msgView.getPoint() + 1);
                break;
            }
            i++;
        }
        // 新用户消息
        if(i == count){
            MsgView msgView = new MsgView(getActivity());
            msgView.setWidgetData(msgUser, viewModel.getCurrUser().getId());
            msgView.setPoint(msgView.getPoint() + 1);
            msgLayout.addView(msgView, 1);
        }
    }

    /**
     * 接收到新的系统消息
     */
    private void getNewSysMsg(TSysMsg sysMsg){
        MsgView sysMsgView = (MsgView) msgLayout.getChildAt(0);
        sysMsgView.setMsgContent(sysMsg.getMsg());
        sysMsgView.setPoint(sysMsgView.getPoint() + 1);
    }
}